package com.hhb.test;

import com.hhb.mapper.UserMapper;
import com.hhb.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Demo03 {

    String resource = "mybatis-config.xml";
    InputStream inputStream = null;
    SqlSession openSession = null;



    @Test
    public void test03()  {


        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            openSession = sqlSessionFactory.openSession();

            UserMapper mapper = openSession.getMapper(UserMapper.class);
            User user = mapper.findUserByIdAndUsername(33, "黄陈浮生");
            System.out.println(user);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            openSession.close();
        }

    }

    @Test
    public void test04()  {


        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            openSession = sqlSessionFactory.openSession();

            UserMapper mapper = openSession.getMapper(UserMapper.class);

            Map<String,Object> map = new HashMap<>();
            map.put("id",33);
            map.put("username","黄陈浮生");
            User userByMap = mapper.findUserByMap(map);
            System.out.println(userByMap);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            openSession.close();
        }

    }

    @Test
    public void test05()  {


        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            openSession = sqlSessionFactory.openSession();

            UserMapper mapper = openSession.getMapper(UserMapper.class);

            User user = new User();
            user.setId(33);
            user.setUsername("黄陈浮生");
            User userByMap = mapper.findUserByModel(user);
            System.out.println(userByMap);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            openSession.close();
        }

    }
}
